const mongoose = require("mongoose");

// 连接数据库
function link() {
    if (mongoose.connection.readyState === 1) return Promise.resolve();
    else mongoose.connect("mongodb://127.0.0.1:27017/user");
}

// 创建schema实例
const schema = new mongoose.Schema({
    userName: {
        type: String,
        required: true,
        unique: true,
    },
    passWord: {
        type: String,
        required: true,
    },
},{
    versionKey:false
});

// 创建文档模型
const userList = mongoose.model("userList", schema, "userList");

// 创建构造函数
function Mon(mod) {
    this.mod = mod;
}

// 往实例原型中增加方法
Object.assign(Mon.prototype, {
    // 添加
    async addUse(obj) {
        await link();
        return this.mod(obj).save();
    },

    // 查找
    async find(obj) {
        await link();
        return this.mod(obj).save();
    },
});

// 返回实例对象
module.exports = new Mon(userList);
